package com.zxcz.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.zxcz.domain.Role;
import com.zxcz.domain.User;
import com.zxcz.service.UserService;

@Configuration
public class MyUserDetailsService implements UserDetailsService{
	@Autowired
	private UserService userService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	private static final Log logger = LogFactory.getLog(MyUserDetailsService.class);
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//根据账号查询出用户
		User user = userService.findUserByAccount(username);
		
		//判断用户是否存在
		if(user == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		
		//获取密码
		String password = user.getPassword();
		String pwVersion = password.substring(2, 3);
		String newPassword = null;
		//兼容其他版本的加密
		if(password.substring(2, 3).equals("a")) {
			newPassword = password;
		}else {
			StringBuffer stringBuffer = new StringBuffer(password);
			stringBuffer.replace(2, 3,"a");
			newPassword = stringBuffer.toString();
		}
		
		//添加角色权限
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		List<Role> roles = user.getRoles();
		for(Role role : roles) {
			grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
		}
		
		return new org.springframework.security.core.userdetails.User(username, newPassword, grantedAuthorities);
	}

	@Bean
	public PasswordEncoder getPasswordEncoder() {
		return new BCryptPasswordEncoder();
	}
}
